<template>
  <a-modal
    :visible="visible"
    @cancel="cancelBtn"
    title="导入结果"
    :footer="null"
  >
    <a-result
      :status="result?.errorFileKey ? 'warning' : 'success'"
      :title="result?.errorFileKey ? '导入出错' : '导入成功'"
      :style="{padding: 0}"
    >
      <template #subTitle>
        <div class="result-sub">成功条数: {{result.successRows || 0}}</div>
        <div class="result-sub">失败条数: {{result.errorRows || 0}}</div>
      </template>
      <template #extra>
        <a-button
          type="primary"
          :loading="loading"
          v-if="result?.errorFileKey"
          @click.stop="downLoadError"
        >下载导入结果</a-button>
      </template>
    </a-result>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  watch,
  ref,
} from "vue";
import request from "../../../../common/utils/request";
import { Result } from "ant-design-vue";
import { TextTip } from "bl-common-vue3";
export default defineComponent({
  name: "ImportResult",
  components: {
    TextTip,
    "a-result": Result,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    result: {
      type: Object,
      default: () => ({}),
    },
    // 下载失败文件的request
    errorUrl: {
      type: Object,
      default: () => ({
        server: '/org',
        url: '/department/user/import/file',
      }),
    },
  },
  setup(props, context) {
    const loading = ref(false);

    const cancelBtn = () => {
      context.emit("cancelBtn");
    };

    const downLoadError = () => {
      loading.value = true;
      request.downLoad(props.errorUrl.server, props.errorUrl.url, {errorFileKey: props.result.errorFileKey}).then((res) => {
        console.log(res);
        loading.value = false;
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", res.fileName || "excel.xlsx");

        document.body.appendChild(link);
        link.click();
        link.remove();
      }).catch(() => {
        loading.value = false;
      });
    };


    watch(
      () => props.visible,
      (val) => {
        if (!val) {
          loading.value = false;
        }
      }
    );

    return {
      loading,
      cancelBtn,
      downLoadError,
    };
  },
});
</script>

<style lang="less" scoped>
.result-sub {
  color: #666;
  line-height: 36px;
}
</style>
